from datetime import datetime
from typing import List, Dict, Optional, Any
from sqlalchemy import func

from sqlalchemy import select
from sqlalchemy.ext.asyncio.session import AsyncSession
from sqlalchemy.orm import Session

from common.sqlalchemy_db import SqlalchemyX
from modules.http_resp import ResponseSuccess
from modules.mod import GroupRelationship, Group
from service.GroupDBService import GroupDBService
from service.GroupRelationshipService import GroupRelationshipService
from service.RandomAvatarService import RandomAvatarService
from service.UserService import UserService
import  uuid


class GroupService:
    def __init__(
        self,
        user_service: UserService= UserService(),
        group_db_service: GroupDBService = GroupDBService(),
        group_relationship_service: GroupRelationshipService = GroupRelationshipService(),
        random_avatar_service: RandomAvatarService = RandomAvatarService(),
        session: AsyncSession = SqlalchemyX.AsyncSessionLocal(),
    ):
        self.session = session
        self.user_service = user_service
        self.group_db_service = group_db_service
        self.group_relationship_service = group_relationship_service
        self.random_avatar_service = random_avatar_service

    async def get_group_list(self, db: AsyncSession, user_id: str) -> ResponseSuccess:
        await self.user_service.check_user_existence({ "user_id": user_id})
        groups = await self.get_user_groups_mes(db, user_id)
        return ResponseSuccess({
                "userId": user_id,
                "groupCounts": len(groups),
                "groupList": groups
            })

    async def get_group_members(self, group_id: str) -> ResponseSuccess:
        await self.check_group_exists(group_id)
        member_ids = await self.get_group_member_ids( group_id)
        members_mes = await self.get_group_members_mes(self.session, member_ids, group_id)
        group_mes = await self.get_group_mes(self.session, {"group_id":group_id})
        return ResponseSuccess({
                "groupId": group_id,
                "groupMes": group_mes,
                "groupMembersCount": len(member_ids),
                "groupMembersMes": members_mes
            }
        )

    async def create_group(
        self,
        group_name: str,
        group_manager_id: str,
        group_type: int
    ) -> Dict:
        if not await self.user_service.check_user_existence({"user_id": group_manager_id}):
            raise ValueError("无效用户")
        if await self.group_db_service.get_group_by({"group_name": group_name}):
            raise ValueError("群组名称已存在")

        group_avatar = await self.random_avatar_service.get_random_avatar_url()
        group_reg_time = datetime.now()

        new_group = await self.group_db_service.create_group(self.session, {
            "group_name": group_name,
            "group_manager_id": group_manager_id,
            "group_avatar": group_avatar,
            "group_reg_time": group_reg_time,
            "group_type": group_type,
            "group_id" : uuid.uuid4(),
        })

        await self.group_relationship_service.create_group_relationship(self.session, {
            "user_id": group_manager_id,
            "group_id": new_group.group_id,
            "top_if":0,
            "group_member_type": "群主"
        })

        return  {
                    "groupId": new_group.group_id,
                    "groupName": new_group.group_name,
                    "groupManagerId": new_group.group_manager_id,
                    "groupAvatar": new_group.group_avatar,
                    "groupRegTime": new_group.group_reg_time,
                    "groupType": new_group.group_type,

                }

    async def get_group_member_ids(self, group_id: str) -> List[str]:
        relations = await self.group_relationship_service.get_group_relationships(self.session, {"group_id": group_id})
        return [rel.user_id for rel in relations]

    async def get_user_groups_mes(self, db: AsyncSession, user_id: str) -> List[Dict]:
        """获取用户的所有群组信息"""
        relations = await self.group_relationship_service.get_group_relationships(self.session, {"user_id": user_id})
        user_ids = [rel.group_id for rel in relations]
        # 创建一个空列表来存储所有群组信息
        all_groups = []
        
        # 遍历每个群组ID，获取群组信息并添加到列表中
        for group_id in user_ids:
            groups = await self.get_group_mes(db, {"group_id": group_id})
            all_groups.extend(groups)  # 使用extend而不是append来避免嵌套列表
        
        return all_groups

    async def check_group_exists(self, group_id: str):
        query = select(func.count()).select_from(Group).where(Group.group_id == group_id)
        result = await self.session.execute(query)
        count = result.scalar()
        return count > 0


    async def get_group_members_mes(
        self,
        db: AsyncSession,
        member_ids: List[str],
        group_id: str
    ) -> List[Dict]:
        members = []
        for user_id in member_ids:
            user_mes = await self.user_service.get_user_basic_mes({"user_id": user_id})
            relation = await self.get_group_relationship(db, user_id, group_id)
            members.append({
                **user_mes,
                "groupMemberType": relation.group_member_type
            })
        return members

    async def get_group_mes(self, db: AsyncSession, option : Dict[str, Any]) -> Dict:
        """ 获取用户的所有群组信息"""
        groupRelationships = await self.group_relationship_service.get_group_relationships(db, option)
        ids = [i.group_id for i in groupRelationships]
        group_query = await db.execute(select(Group).where(Group.group_id.in_(ids)))
        groups = group_query.scalars().all()
        return [
            {
                "group_id": group.group_id,
                "group_name": group.group_name,
                "group_manager_id": group.group_manager_id,
                "group_avatar": group.group_avatar,
                "group_reg_time": group.group_reg_time,
                "group_type": group.group_type
            } for group in groups
        ]

    async def get_user_group_mes(self, db: AsyncSession, userId: str) -> Dict:
        groupRelationships = await self.group_relationship_service.get_group_relationships(db, {"user_id": userId})
        ids = [i.group_id for i in groupRelationships]
        group_query = await db.execute(select(Group).where(Group.group_id.in_(ids)))
        groups = group_query.scalars().all()

        # Convert Group objects to dictionaries
        return [
            {
                "group_id": group.group_id,
                "group_name": group.group_name,
                "group_manager_id": group.group_manager_id,
                "group_avatar": group.group_avatar,
                "group_reg_time": group.group_reg_time,
                "group_type": group.group_type
            } for group in groups
        ]

    async def get_group(self, db: AsyncSession,option) -> Group:
        group = await db.execute(select(Group).filter_by(**option))
        return group.scalars().first()

    async def get_group_relationship(
        self,
        db: AsyncSession,
        user_id: str,
        group_id: str
    ) -> GroupRelationship:
        relations = await self.group_relationship_service.get_group_relationships(db, {
            "user_id": user_id,
            "group_id": group_id
        })
        return relations[0]